package uk.ac.lkl.lpp.ui;



import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JCheckBox;
import javax.swing.JPanel;

import javax.swing.table.TableColumnModel;
import javax.swing.table.TableColumn;

import uk.ac.lkl.lpp.model.FieldGroup;
import uk.ac.lkl.lpp.model.TeachingMethodTableModel;

import uk.ac.lkl.lpp.model.ldo.TeachingMethod;


public class TeachingMethodFieldGroupHandler extends JPanel {

    private TeachingMethodTableModel tableModel;

    private FieldGroup<TeachingMethod> fieldGroup;

    private TableColumnModel columnModel;

    /**
     * Map from table column to preferred width
     * 
     */
    private HashMap<TableColumn, Integer> tableColumnMap;

    private JCheckBox visibilityCheckBox;


    public TeachingMethodFieldGroupHandler(TeachingMethodTableModel tableModel,
            TableColumnModel columnModel,
            FieldGroup<TeachingMethod> fieldGroup,
            ArrayList<TableColumn> tableColumns) {
        this.tableModel = tableModel;
        this.columnModel = columnModel;
        this.fieldGroup = fieldGroup;
        this.tableColumnMap = new HashMap<TableColumn, Integer>();
        initialiseTableColumnMap(tableColumns);

        String fieldGroupName = fieldGroup.getName();
        visibilityCheckBox = new JCheckBox(fieldGroupName);
        add(visibilityCheckBox);
        visibilityCheckBox.setSelected(true);

        visibilityCheckBox.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                processActionPerformed();
            }
        });

    }


    private void initialiseTableColumnMap(ArrayList<TableColumn> tableColumns) {
        for (TableColumn tableColumn : tableColumns) {
            int preferredWidth = tableColumn.getPreferredWidth();
            tableColumnMap.put(tableColumn, preferredWidth);
        }
    }


    private void processActionPerformed() {
        if (visibilityCheckBox.isSelected())
            for (Map.Entry<TableColumn, Integer> entry : tableColumnMap
                    .entrySet()) {
                TableColumn tableColumn = entry.getKey();
                int preferredWidth = entry.getValue();
                tableColumn.setPreferredWidth(preferredWidth);
            }
        else
            for (TableColumn tableColumn : tableColumnMap.keySet()) {
                int preferredWidth = tableColumn.getPreferredWidth();
                tableColumnMap.put(tableColumn, preferredWidth);
                tableColumn.setMinWidth(0);
                tableColumn.setPreferredWidth(0);
            }
    }
}
